package com.h3c.gm.schedule.task

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.h3c.gm.common.constant.HostOrgkeyPair
import com.h3c.gm.common.constant.ScheduleURI
import com.h3c.gm.common.utils.HttpUtils
import com.h3c.gm.common.utils.SpringContextUtil
import com.h3c.gm.common.utils.UUIDUtils
import com.h3c.gm.entity.DO.SysOrgQuotaDO
import com.h3c.gm.service.SysOrgQuotaService
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/**
 * Created by d14287 on 2017/7/7.
 */
class QuotaTask implements Runnable {
    static Logger logger = LoggerFactory.getLogger(QuotaTask.class)
    HostOrgkeyPair hostOrgkeyPair

    SysOrgQuotaService sysOrgQuotaService = SpringContextUtil.getBean(SysOrgQuotaService.class)

    @Override
    void run() {
        Optional<JSONArray> optional = HttpUtils.httpGet(hostOrgkeyPair.getProc() + '://' + hostOrgkeyPair.getHost() + ScheduleURI.quota_api_uri.replace('{host}', hostOrgkeyPair.getHost()))
        if (!optional.isPresent()) {
            return
        }
        sysOrgQuotaService.deleteByOrgkey(hostOrgkeyPair.name())
        JSONArray arrays = optional.get()
        for (int i = 0; i < arrays.size(); i++) {
            JSONObject object = arrays.getJSONObject(i)
            SysOrgQuotaDO sysOrgQuotaDO = new SysOrgQuotaDO()
            sysOrgQuotaDO.setId(UUIDUtils.generateUUID())
            sysOrgQuotaDO.setQuotacount('-1'.equals(object.getString('quotaquantity')) ? 0L : object.getLong('quotaquantity'))
            sysOrgQuotaDO.setQuotaused(object.getLong('usedquantity'))
            sysOrgQuotaDO.setDeptquota(object.getLong('orgused'))
            sysOrgQuotaDO.setQtype(object.getString('quotacode'))
            sysOrgQuotaDO.setPropname(object.getString('quotaname'))
            sysOrgQuotaDO.setOrgkey(hostOrgkeyPair.name())
            sysOrgQuotaService.insert(sysOrgQuotaDO)
        }
    }

    QuotaTask(HostOrgkeyPair hostOrgkeyPair) {
        this.hostOrgkeyPair = hostOrgkeyPair
    }
}
